﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NetDon.OA.Business;
using NetDon.OA.Data.EntityClasses;
using NetDon.OA.Interface;
using NetDon.OA.Interface.CRM;
using NetDon.OA.Interface.Common;
using NetDon.OA.Interface.Configuration;
using NetDon.OA.Portal.Constants;
using NetDon.Utilities;
using NetDon.WebControls;

namespace NetDon.OA.Portal.Clerk
{

    public partial class OnWayTrackEdit : NavigationPageBase
    {
        private bool OnWayTrackCompleted { get; set; }
        protected Guid Id
        {
            set { ViewState["Id"] = value; }
            get
            {
                if (ViewState["Id"] != null)
                    return ViewState["Id"].ToString().ToGuid();
                return Guid.Empty;
            }
        }

        protected string GoodsCurrentPlace
        {
            set { ViewState["GoodsCurrentPlace"] = value; }
            get
            {
                if (ViewState["GoodsCurrentPlace"] != null)
                    return ViewState["GoodsCurrentPlace"].ToString();
                return string.Empty;
            }
        }

        private IList<IssuingOrderOnWayTrackCommentData> IssuingOrderOnWayTrackComments
        {
            set { ViewState["IssuingOrderOnWayTrackComments"] = value; }
            get
            {
                if (ViewState["IssuingOrderOnWayTrackComments"] != null)
                    return ViewState["IssuingOrderOnWayTrackComments"] as IList<IssuingOrderOnWayTrackCommentData>;
                return new List<IssuingOrderOnWayTrackCommentData>();
            }
        }

        protected override IList<Guid> Ids
        {
            get
            {
                if (string.IsNullOrWhiteSpace(this.fieldIds.Value))
                    return new List<Guid>();
                return this.fieldIds.Value.Split(new char[] { ',' }).Select(id => id.ToGuid()).ToList();

            }
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);




        }
        void ClearInitialDropdown()
        {


        }
        protected void Page_Load(object sender, EventArgs e)
        {
            txtGoodsDelayedDays.Attributes.Add("readonly", "readonly");
            txtActualDeliveredDate_CalendarExtender1.Format = SystemConfiguration.DateFormat;

            //this.txtPlannedGoodsDeliveredDate.Attributes.Add("onchange", "calculateDelayedDays(this);");
            this.txtActualDeliveredDate.Attributes.Add("onchange", "calculateDelayedDays(this);");
            this.txtGoodsTravelDays.Attributes.Add("onchange", "calculatePlannedGoodsDeliveredDate();");
            ddlGoodsTravelDaysUnit.Attributes.Add("onchange", "calculatePlannedGoodsDeliveredDate();");

            if (!IsPostBack)
            {
                CancelButton = btnCancel;

            }
        }

        private void LoadInitialView()
        {
            CurrentIndex = -1;
            LoadUserControl(Ids.Count > 0 ? Ids[++CurrentIndex] : Guid.Empty);

            SetButtonState(Ids.Count <= 0, true, false, Ids.Count == 1);
        }

        public void LoadUserControl(Guid id)
        {
            Id = id;


            var orderService = ServiceContainer.GetService<IIssuingOrderOnWayTrackService>();
            var onWayTrackData = orderService.GetIssuingOrderOnWayTrack(Id);
            //fieldOrderQuantity.Value = issuingOrderData.OrderQuantity.ToString();
            ClearInitialDropdown();
            FormPanelIssuringOrderInfo.DataSource = onWayTrackData;
            FormPanelIssuringOrderInfo.DataBind();
            GoodsCurrentPlace = onWayTrackData.GoodsCurrentPlace;

            if (onWayTrackData.PlannedGoodsDeliveredDate.HasValue)
            {
                txtPlannedGoodsDeliveredDate.Text = onWayTrackData.PlannedGoodsDeliveredDate.Value.ToString("yyyy-MM-dd");
                txtPlannedGoodsDeliveredDateHour.Text = onWayTrackData.PlannedGoodsDeliveredDate.Value.ToString("HH");
            }
            else
            {
                txtPlannedGoodsDeliveredDate.Text = txtPlannedGoodsDeliveredDateHour.Text = string.Empty;
            }
            if (onWayTrackData.ActualDeliveredDate.HasValue)
            {
                txtActualDeliveredDate.Text = onWayTrackData.ActualDeliveredDate.Value.ToString("yyyy-MM-dd");
                txtActualDeliveredDateHour.Text = onWayTrackData.ActualDeliveredDate.Value.ToString("HH");
            }
            else
            {
                txtActualDeliveredDate.Text = txtActualDeliveredDateHour.Text = string.Empty;
            }


            var issuingOrderService = ServiceContainer.GetService<IIssuingOrderService>();
            var issuingOrderData = issuingOrderService.GetIssuingOrder(onWayTrackData.IssuingOrderId);

            FormPanelBasicInfo.DataSource = issuingOrderData;
            FormPanelBasicInfo.DataBind();
            var issuingOrderVehicleInfo = issuingOrderService.GetIssuingOrderVehicleInfo(onWayTrackData.IssuingOrderId);
            GridViewDriverInfo.DataSource = issuingOrderVehicleInfo;
            GridViewDriverInfo.DataBind();

            var issuingOrderDeliveries = issuingOrderService.GetIssuingOrderDeliveryByOrderId(onWayTrackData.IssuingOrderId);
            GridViewOrderDelivery.DataSource = issuingOrderDeliveries;
            GridViewOrderDelivery.DataBind();


            if (issuingOrderData.StartShippmentDate.HasValue)
            {
                hiddenStartShippmentDate.Value = issuingOrderData.StartShippmentDate.Value.ToString("yyyy-MM-dd HH:mm:ss");
            }
            else
            {
                hiddenStartShippmentDate.Value = string.Empty;
            }

            if (onWayTrackData.GoodsDelayedDays > 0)
            {
                this.txtGoodsDelayedDays.Style.Add("color", "#FF6600");
            }
            if (string.IsNullOrWhiteSpace(this.txtGoodsTravelDays.Text))
            {
                var service = ServiceContainer.GetService<IGoodsTravelDaysConfigService>();
                var goodsTravelConfigData =
                    service.GetGoodsTravelDaysConfigDatasByCondition(issuingOrderDeliveries, issuingOrderData);

                if (goodsTravelConfigData!=null)
                {
                    txtGoodsTravelDays.Text = (goodsTravelConfigData.GoodsTravelDays??0).ToString();
                    if (goodsTravelConfigData.GoodsTravelDaysUnit.HasValue)
                        ddlGoodsTravelDaysUnit.SelectedValue = goodsTravelConfigData.GoodsTravelDaysUnit.Value.ToString();

                }
            }
            else
            {
                if (onWayTrackData.GoodsTravelDaysUnit.HasValue)
                    ddlGoodsTravelDaysUnit.SelectedValue = onWayTrackData.GoodsTravelDaysUnit.Value.ToString();
            }

            var plannedGoodsDeliveredDate =
                (issuingOrderData.StartShippmentDate ?? DateTime.Now);
            if (ddlGoodsTravelDaysUnit.SelectedValue == "0") //day
            {
                plannedGoodsDeliveredDate = plannedGoodsDeliveredDate.AddDays(txtGoodsTravelDays.Text.ToInt32() ?? 0);
            }
            else
            {
                plannedGoodsDeliveredDate = plannedGoodsDeliveredDate.AddHours(txtGoodsTravelDays.Text.ToInt32() ?? 0);
            }

            if (string.IsNullOrWhiteSpace(txtPlannedGoodsDeliveredDate.Text))
            {
                txtPlannedGoodsDeliveredDate.Text = plannedGoodsDeliveredDate.ToString("yyyy-MM-dd");
            }

            if (string.IsNullOrWhiteSpace(txtPlannedGoodsDeliveredDateHour.Text))
            {
                txtPlannedGoodsDeliveredDateHour.Text = plannedGoodsDeliveredDate.ToString("HH");
            }

            //if (string.IsNullOrWhiteSpace(txtActualDeliveredDate.Text))
            //{
            //    txtActualDeliveredDate.Text = plannedGoodsDeliveredDate.ToString("yyyy-MM-dd");
            //}

            //if (string.IsNullOrWhiteSpace(txtActualDeliveredDateHour.Text))
            //{
            //    txtActualDeliveredDateHour.Text = plannedGoodsDeliveredDate.ToString("HH");
            //}


            IssuingOrderOnWayTrackComments = orderService.GetIssuingOrderOnWayTrackCommentById(Id).ToList();
            AddEmptyIssuingOrderDeliveryAndBind();
            OrderStatus = issuingOrderData.OrderStatus;
            OnWayTrackCompleted = OrderStatus == OrderStatus.OnWayTrackCompleted &&
                                 !onWayTrackData.ActualDeliveredDate.HasValue;
            FormPanelIssuringOrderInfo.Enabled = IsEditable();

        }

        protected override bool IsEditable()
        {
            if (IsManager()) return true;
            return OrderStatus == OrderStatus.Entrucked;
        }


        void SetButtonState(bool isAdd, bool isFirst, bool isLast, bool isSingleEdit)
        {

            SetButtonState(isAdd, isFirst, isLast, isSingleEdit, this.btnSave, btnCancel, btnPrevious, btnNext, btnSaveAndPrevious, btnSaveAndNext, panelBasic);

        }

        public bool SaveOrder()
        {
            DateTime actualDeliveredDate = DateTime.MinValue;
            if (!string.IsNullOrWhiteSpace(txtActualDeliveredDate.Text))
            {
                if (!DateTime.TryParse(txtActualDeliveredDate.Text, out actualDeliveredDate))
                {
                    //Alert("请输入合法的实际到达时间。");
                    return false;
                }
            }
            int actualDeliveredDateHour = 0;

            if (!string.IsNullOrWhiteSpace(this.txtActualDeliveredDateHour.Text) && !int.TryParse(this.txtActualDeliveredDateHour.Text, out actualDeliveredDateHour))
            {
                Alert("请输入正确的实际到达小时数。");
                return false;
            }
            var service = ServiceContainer.GetService<IIssuingOrderOnWayTrackService>();
            var onWayTrackData = service.GetIssuingOrderOnWayTrack(Id);
            var goodsTravelDays = this.txtGoodsTravelDays.Text.ToInt32();
            onWayTrackData.GoodsTravelDays = goodsTravelDays;
            onWayTrackData.GoodsTravelDaysUnit = int.Parse(this.ddlGoodsTravelDaysUnit.SelectedValue);

            DateTime plannedGoodsDeliveredDate;
            if (DateTime.TryParse(hiddenStartShippmentDate.Value, out plannedGoodsDeliveredDate))
            {

                if (goodsTravelDays.HasValue)
                {
                    plannedGoodsDeliveredDate = onWayTrackData.GoodsTravelDaysUnit == 0 ? plannedGoodsDeliveredDate.AddDays(goodsTravelDays.Value) : plannedGoodsDeliveredDate.AddHours(goodsTravelDays.Value);
                }
                onWayTrackData.PlannedGoodsDeliveredDate = plannedGoodsDeliveredDate;
            }
            else
            {
                onWayTrackData.PlannedGoodsDeliveredDate = null;
            }
            if (actualDeliveredDate.Date != DateTime.MinValue)
                onWayTrackData.ActualDeliveredDate = actualDeliveredDate.AddHours(actualDeliveredDateHour);
            else
            {
                onWayTrackData.ActualDeliveredDate = null;
            }
            if (GoodsCurrentPlace.Trim() != this.txtGoodsCurrentPlace.Text.Trim())
            {
                onWayTrackData.GoodsCurrentPlace = this.txtGoodsCurrentPlace.Text.Trim();
                onWayTrackData.LastGoodsCurrentPlaceUpdatedDate = DateTime.Now;
                onWayTrackData.LastGoodsCurrentPlaceUpdatedBy = CurrentApplicationContext.UserId;
                onWayTrackData.NewIssuingOrderOnWayTrackHistory = new IssuingOrderOnWayTrackHistoryData();

                onWayTrackData.NewIssuingOrderOnWayTrackHistory.GoodsCurrentPlace = this.txtGoodsCurrentPlace.Text.Trim();
                onWayTrackData.NewIssuingOrderOnWayTrackHistory.LastUpdatedDate = DateTime.Now;
                onWayTrackData.NewIssuingOrderOnWayTrackHistory.LastUpdatedBy = CurrentApplicationContext.UserId;
                onWayTrackData.NewIssuingOrderOnWayTrackHistory.IssuingOrderOnWayTrackId = onWayTrackData.Id;

            }

            if(onWayTrackData.ActualDeliveredDate.HasValue && onWayTrackData.PlannedGoodsDeliveredDate.HasValue )
            {
                onWayTrackData.GoodsDelayedDays =
                    (onWayTrackData.ActualDeliveredDate.Value - onWayTrackData.PlannedGoodsDeliveredDate.Value).Days;
            }

            onWayTrackData.IsGoodsDelayed = onWayTrackData.GoodsDelayedDays > 0;
            onWayTrackData.IsGoodsExceptional = IssuingOrderOnWayTrackComments.Count(o => !string.IsNullOrWhiteSpace(o.GoodsDelayedReasons)) > 0;

            if (goodsTravelDays.HasValue)
            {
                onWayTrackData.GoodsTravelDays = goodsTravelDays.Value;
            }
            onWayTrackData.LastUpdatedBy = CurrentApplicationContext.UserId;
            onWayTrackData.LastUpdatedDate = DateTime.Now;

            ExtractIssuingOrderDelivery();
            onWayTrackData.IssuingOrderOnWayTrackCommentList = IssuingOrderOnWayTrackComments;

            var result = service.ModifyIssuingOrderOnWayTrack(onWayTrackData);
            if (result)
            {
                Success("保存成功!");
            }

            return result;


        }

        private bool IsLastRow(int rowIndex)
        {
            return IssuingOrderOnWayTrackComments.Count() == rowIndex + 1;
        }

        protected void gridIssuingOrderDelivery_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var issuingOrderOnWayTrackCommentId = (e.Row.DataItem as IssuingOrderOnWayTrackCommentData).Id.ToString();

                var btnDelete = (ImageButton)e.Row.FindControl("btnDelete");
                if (btnDelete != null)
                {
                    btnDelete.OnClientClick = string.Format("deleteIssuingOrderDeliveryId('{0}');return false;",
                                                            issuingOrderOnWayTrackCommentId);
                }

                var txtGoodsDelayedReasons = (TextBox)e.Row.FindControl("txtGoodsDelayedReasons");
                var txtExceptions = (TextBox)e.Row.FindControl("txtExceptions");

                txtGoodsDelayedReasons.Attributes.Remove("onblur");
                //if (IsLastRow(e.Row.RowIndex))
                //{
                txtGoodsDelayedReasons.Attributes.Add("onblur",
                                                    "onChangeGoodsDelayedReasons(this,'" + txtExceptions.ClientID +
                                                    "');return false;");
                //}
            }
        }


        public void btnGoodsDelayedReasons_Click(object sender, EventArgs e)
        {

            if (!string.IsNullOrWhiteSpace(hiddengoodsDelayedReasons.Value))
            {
                ExtractIssuingOrderDelivery();
            }

            AddEmptyIssuingOrderDeliveryAndBind();

        }

        private void AddEmptyIssuingOrderDeliveryAndBind()
        {
            var tempIssuingOrderOnWayTrackComments = IssuingOrderOnWayTrackComments;
            tempIssuingOrderOnWayTrackComments.Add(new IssuingOrderOnWayTrackCommentData()
            {
                Id = Guid.NewGuid(),
                GoodsDelayedReasons = string.Empty

            });
            IssuingOrderOnWayTrackComments = tempIssuingOrderOnWayTrackComments; //update viewstate
            gridOrderDetailList.DataSource = IssuingOrderOnWayTrackComments;
            gridOrderDetailList.DataBind();
        }

        private void ExtractIssuingOrderDelivery()
        {
            var tempIssuingOrderOnWayTrackComments = new List<IssuingOrderOnWayTrackCommentData>();
            foreach (GridViewRow detailRow in gridOrderDetailList.Rows)
            {
                var issuingOrderOnWayTrackCommentId = gridOrderDetailList.DataKeys[detailRow.RowIndex]["Id"].ToString().ToGuid();
                var issuingOrderOnWayTrackComment = IssuingOrderOnWayTrackComments.FirstOrDefault(src => src.Id == issuingOrderOnWayTrackCommentId);

                if (issuingOrderOnWayTrackComment != null)
                {
                    issuingOrderOnWayTrackComment.IssuingOrderOnWayTrackId = Id;

                    issuingOrderOnWayTrackComment.Exceptions = (detailRow.FindControl("txtExceptions") as TextBox).Text;
                    issuingOrderOnWayTrackComment.GoodsDelayedReasons = (detailRow.FindControl("txtGoodsDelayedReasons") as TextBox).Text;
                    issuingOrderOnWayTrackComment.Remark = (detailRow.FindControl("txtRemark") as TextBox).Text;

                    tempIssuingOrderOnWayTrackComments.Add(issuingOrderOnWayTrackComment);
                }

            }

            //update viewstate
            IssuingOrderOnWayTrackComments = tempIssuingOrderOnWayTrackComments;
        }

        protected void btnhiddenIssuingOrderOnWayTrackCommentDelete_Click(object sender, EventArgs e)
        {
            var issuingOrderDeliveryId = hiddenIssuingOrderOnWayTrackCommentId.Value.ToGuid();
            var issuingOrderDelivery =
                IssuingOrderOnWayTrackComments.FirstOrDefault(src => src.Id == issuingOrderDeliveryId);
            if (issuingOrderDelivery != null)
            {
                IssuingOrderOnWayTrackComments.Remove(issuingOrderDelivery);
                //delete from database
                var service = ServiceContainer.GetService<IIssuingOrderOnWayTrackService>();
                service.RemoveIssuingOrderOnWayTrackComment(issuingOrderDeliveryId);
            }

            gridOrderDetailList.DataSource = IssuingOrderOnWayTrackComments;
            gridOrderDetailList.DataBind();
        }

        protected void btnReLoadIds_Click(object sender, EventArgs e)
        {
            LoadInitialView();
            btnReLoadIds.Enabled = false;
        }


        protected void btnSaveAndNext_Click(object sender, EventArgs e)
        {
            if (SaveOrder())
            {

                btnNext_Click(sender, e);

            }
        }
        protected void btnSaveAndPrevious_Click(object sender, EventArgs e)
        {
            if (SaveOrder())
            {

                btnPrevious_Click(sender, e);

            }
        }
        protected void btnNext_Click(object sender, EventArgs e)
        {

            if (HasNextView())
            {
                LoadNavigationView(Ids[++CurrentIndex]);
            }

            SetButtonState(false, IsFirstView, IsLastView, false);



        }
        protected void btnPrevious_Click(object sender, EventArgs e)
        {
            if (HasPreviousView())
            {
                LoadNavigationView(Ids[--CurrentIndex]);

            }
            SetButtonState(false, IsFirstView, IsLastView, false);
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (SaveOrder())
            {
                CloseWindow(true);
            }

        }



        internal void LoadNavigationView(Guid id)
        {

            Id = id;

            LoadUserControl(id);

        }


    }
}